import random
import string
from flask import Blueprint, render_template, request, redirect, url_for, jsonify, flash, session
from flask_mail import Message
from werkzeug.security import generate_password_hash, check_password_hash
from blueprints.forms import RegisterForm, LoginForm
import logging
from models import EmailCaptchaModel, UserModel

from exts import mail, db

# 创建蓝图对象
blueprints = Blueprint('auth', __name__, url_prefix='/auth')


@blueprints.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        try:
            form = LoginForm(request.form)
            if form.validate():
                username = form.username.data
                password = form.password.data
                user = UserModel.query.filter_by(username=username).first()
                if user and check_password_hash(user.password, password):
                    # 登录成功，保存用户信息到session中
                    flash('登录成功')
                    session['user_id'] = user.id
                    return redirect(url_for('qa.index'))
                # 验证用户名和密码
                else:
                    flash('用户名或密码错误')
                    return render_template('login.html')

            logging.debug(f"输入错误: {form.errors}")
            return jsonify({'code': 400, 'message': '输入错误', 'error': form.errors})
        except Exception as e:
            logging.error(f"登录失败: {e}")
            return jsonify({'code': 400, 'message': '登录失败', 'error': str(e)})
    return render_template('login.html')


@blueprints.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        try:
            form = RegisterForm(request.form)
            logging.debug(f"表单数据: {form.data}")
            if form.validate():
                email = form.email.data
                username = form.username.data
                password = form.password.data
                logging.debug(f"用户名: {username}, 密码: {password}")
                # 将用户信息保存到数据库中
                user = UserModel(email=email, username=username, password=generate_password_hash(password))
                db.session.add(user)
                db.session.commit()
                logging.debug("用户信息已保存到数据库")
                flash('注册成功')
                return redirect(url_for('auth.login'))
            else:
                logging.debug(f"表单验证失败: {form.errors}")
                flash('注册失败')
                return jsonify({'code': 400, 'message': '表单验证失败', 'error': form.errors})
        except Exception as e:
            logging.error(f"注册失败: {e}")
            db.session.rollback()
            flash('注册失败')
            return jsonify({'code': 400, 'message': '注册失败', 'error': str(e)})
    return render_template('register.html', form=RegisterForm())


@blueprints.route('/captcha/email', methods=['GET', 'POST'])
def get_email_captcha():
    if request.method == 'POST':
        email = request.form.get('email')
        if not email:
            flash('请输入邮箱')
            return redirect(url_for('auth.register'))
        # 生成验证码
        captacha = ''.join(random.sample(string.digits * 6, k=6))
        # 将验证码保存到数据库中
        # 推荐使用redis/memcached
        email_captcha = EmailCaptchaModel(email=email, captcha=captacha)
        db.session.add(email_captcha)
        db.session.commit()
        msg = Message(
            subject='验证码',
            recipients=[email],
            body=f'您的验证码是：{captacha},请勿泄露给他人'

        )
        mail.send(msg)
        flash('验证码已发送到邮箱')
        return jsonify({'code': 200, 'message': '验证码已发送到邮箱', 'data': None})


@blueprints.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('auth.login'))
